package com.bawei.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

//import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

public class SpringMvcFileDownload {

	/**
	 * @param fileFullPath 要下载的文件全路径
	 * @param saveAsFileName 下载文件的文件名，用来在浏览器另存为对话框中显示。
	 * @return
	 * @throws IOException
	 */
	public static ResponseEntity<byte[]> download(File fileFullPath,String saveAsFileName) throws IOException {
		String fileName = new String(saveAsFileName.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
		HttpHeaders headers = new HttpHeaders();
		
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		byte[] byteArray = FileCopyUtils.copyToByteArray(fileFullPath);
//		byte[] byteArray = FileUtils.readFileToByteArray(fileFullPath);
		return new ResponseEntity<byte[]>(byteArray,headers, HttpStatus.CREATED);
	}
	
	public static File upload(MultipartFile file,HttpServletRequest request){
		String newFileName =null;
		File upload = null;
		if(file!=null && file.getSize()>0){//file.getSize()是文件的大小。1.jpg,1.jpg，1.doc
			//重命名
			UUID uuid = UUID.randomUUID();
			System.out.println(uuid.toString());
			String name = uuid.toString().replaceAll("-", "");//把uuid变成string，并且替换掉里面的“-”
			System.out.println("去掉所有横杠："+name);
			//获取扩展名：
			String filename = file.getOriginalFilename();//获取用户上传的时候的提交过来的文件名 2018.7.jpg
			int index = filename.lastIndexOf(".");//获取最后面的点号的位置
			String ext = filename.substring(index);//获取到扩展名：.jpg
			newFileName = name + ext;
			
			//获取webroot里面的upload文件夹的路径
			String realPath = request.getSession().getServletContext().getRealPath("upload");
			File file2 = new File(realPath);
			if(!file2.exists()){
				file2.mkdirs();//新建文件夹
			}
			//新建空白文件
			upload = new File(realPath + File.separator + newFileName);
			
			try {
				//把上传过来的文件内容，复制到空白文件upload
				file.transferTo(upload);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return upload;
	}
	
}
